﻿using Sharp.WeShare.Common;
using System;

namespace Sharp.WeShare.MP
{
    /// <summary>
    /// 全局接口调用凭据实体类
    /// </summary>
    public class AccessToken :BaseRes
    {
        public string access_token { get; set; }
        public int expires_in { get; set; }

        private static object locker = new object();
        /// <summary>
        /// 获取access_token，并在获取失败后，返回失败原因。
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <param name="errmsg"></param>
        /// <returns></returns>
        public static string GetValue(string appId,string appSecret,out string errmsg)
        {
            errmsg = "";
            lock (locker)
            {
                var value = CacheHelper.GetValue(appId);
                if(string.IsNullOrEmpty(value))
                {
                    string url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={appSecret}";
                    AccessToken accesstoken = Utils.GetResult<AccessToken>(url);
                    if (accesstoken.errcode == 0)
                    {
                        CacheHelper.Add(appId, accesstoken.access_token, DateTime.Now.AddSeconds(accesstoken.expires_in / 2));
                        value = accesstoken.access_token;
                    }else
                    {
                        errmsg = accesstoken.errmsg;
                    }
                }
                return value;
            }
        }
        /// <summary>
        /// 获取access_token
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public static string GetValue(string appId,string appSecret)
        {
            string errmsg;
            return GetValue(appId, appSecret, out errmsg);
        }
        /// <summary>
        /// 强制刷新。用于在未知原因导致的access_ken实效的情况下，强制刷新。由于access_token的接口调用次数限制，请慎用此接口。
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <param name="errmsg"></param>
        /// <returns></returns>
        public static string Refresh(string appId, string appSecret, out string errmsg)
        {
            errmsg = "";
            string url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={appSecret}";
            AccessToken accesstoken = Utils.GetResult<AccessToken>(url);
            if (accesstoken.errcode == 0)
            {
                CacheHelper.Refresh(appId, accesstoken.access_token, DateTime.Now.AddSeconds(accesstoken.expires_in / 2));
            }
            else
            {
                errmsg = accesstoken.errmsg;
            }
            return accesstoken.access_token;
        }
    }
}
